<template>
  <div class="pet-list-container">
    <el-card class="filter-card">
      <div class="filter-section">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="选择宠物状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="待领养" value="1"></el-option>
              <el-option label="已确定领养" value="2"></el-option>
              <el-option label="已领养" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="queryParams.categoryId"
              placeholder="选择宠物分类"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="category in topCategories"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="queryParams.keyword"
              placeholder="输入宠物名称"
              clearable
              style="width: 220px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="list-card">
      <div class="list-header">
        <h2 class="list-title">
          {{ getListTitle() }}
          <el-tag v-if="queryParams.status" type="info">{{
            queryParams.status === "1"
              ? "待领养"
              : queryParams.status === "2"
              ? "已确定领养"
              : "已领养"
          }}</el-tag>
        </h2>
        <div class="list-info">
          共 <span class="highlight">{{ total }}</span> 条记录
        </div>
      </div>

      <div v-loading="loading" class="pet-list">
        <div v-if="petList.length === 0" class="empty-data">暂无宠物数据</div>
        <el-row :gutter="20" v-else>
          <el-col
            v-for="pet in petList"
            :key="pet.recipeId"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card
              class="pet-card"
              shadow="hover"
              @click="goToDetail(pet.recipeId)"
            >
              <div class="pet-image">
                <el-image
                  :src="pet.coverImage || ''"
                  fit="cover"
                  style="width: 100%; height: 180px"
                ></el-image>
                <div class="pet-status">
                  <el-tag
                    :type="
                      pet.status === '1'
                        ? 'warning'
                        : pet.status === '2'
                        ? 'info'
                        : 'success'
                    "
                  >
                    {{
                      pet.status === "1"
                        ? "待领养"
                        : pet.status === "2"
                        ? "已确定领养"
                        : "已领养"
                    }}
                  </el-tag>
                </div>
              </div>
              <div class="pet-info">
                <h3 class="pet-name">{{ pet.recipeName }}</h3>
                <p class="pet-category">
                  分类:
                  {{ pet.categoryName || getCategoryName(pet.categoryId) }}
                </p>
                <div class="pet-meta">
                  <span>{{ pet.age }}岁</span>
                  <span>{{
                    pet.gender === 1 ? "公" : pet.gender === 2 ? "母" : "未知"
                  }}</span>
                </div>
                <p class="pet-description">{{ pet.description }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[8, 16, 24, 36]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { listRecipe } from "@/api/recipe";
import { treeCategory } from "@/api/category";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

// 列表数据
const loading = ref(false);
const petList = ref([]);
const total = ref(0);

// 分类数据
const categoryOptions = ref([]);
const topCategories = computed(() => {
  return categoryOptions.value.filter(
    (item) => !item.parentId || item.parentId === 0
  );
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
  status: route.query.status || "",
  categoryId: route.query.categoryId || "",
  keyword: "",
  orderByColumn: "create_time",
  isAsc: "desc",
});

// 获取列表标题
const getListTitle = () => {
  if (queryParams.categoryId) {
    const category = topCategories.value.find(
      (item) => item.categoryId === queryParams.categoryId
    );
    return category ? category.categoryName + "宠物" : "宠物列表";
  }
  return queryParams.status === "1" ? "待领养宠物" : "宠物列表";
};

// 获取分类数据
const getCategoryData = async () => {
  try {
    const res = await treeCategory();
    if (res.code === 200 && res.data) {
      categoryOptions.value = res.data;
    } else {
      useMockCategoryData();
    }
  } catch (error) {
    console.error("获取分类数据失败:", error);
    useMockCategoryData();
  }
};

// 使用模拟分类数据
const useMockCategoryData = () => {
  categoryOptions.value = [
    {
      categoryId: 1,
      categoryName: "猫咪",
      children: [
        { categoryId: 4, categoryName: "英短" },
        { categoryId: 5, categoryName: "加菲" },
        { categoryId: 6, categoryName: "暹罗" },
      ],
    },
    {
      categoryId: 2,
      categoryName: "狗狗",
      children: [
        { categoryId: 7, categoryName: "金毛" },
        { categoryId: 8, categoryName: "哈士奇" },
        { categoryId: 9, categoryName: "泰迪" },
      ],
    },
    {
      categoryId: 3,
      categoryName: "其他宠物",
      children: [
        { categoryId: 10, categoryName: "兔子" },
        { categoryId: 11, categoryName: "仓鼠" },
      ],
    },
  ];
};

// 获取宠物列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listRecipe(queryParams);
    if (res.code === 200) {
      petList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || "获取宠物列表失败");
      useMockPetData();
    }
  } catch (error) {
    console.error("获取宠物列表失败:", error);
    ElMessage.error("获取宠物列表失败，显示模拟数据");
    useMockPetData();
  } finally {
    loading.value = false;
  }
};

// 使用模拟宠物数据
const useMockPetData = () => {
  const mockData = [];
  const count = queryParams.pageSize || 8;
  for (let i = 0; i < count; i++) {
    const status =
      queryParams.status || (i % 3 === 0 ? "1" : i % 3 === 1 ? "2" : "3");
    // 如果指定了状态，但模拟数据与查询不符，则跳过
    if (queryParams.status && status !== queryParams.status) continue;

    // 如果指定了分类，但模拟数据与查询不符，则跳过
    const categoryId = i % 3 === 0 ? 1 : i % 3 === 1 ? 2 : 3;
    if (
      queryParams.categoryId &&
      parseInt(queryParams.categoryId) !== categoryId
    )
      continue;

    mockData.push({
      recipeId: i + 1,
      recipeName: `${
        status === "1" ? "待领养" : status === "2" ? "已确定领养" : "已领养"
      }的${i % 2 === 0 ? "小猫" : "小狗"}${i + 1}`,
      categoryId: categoryId,
      coverImage:
        i % 2 === 0
          ? "https://img0.baidu.com/it/u=1394778073,2898249422&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333"
          : "https://img1.baidu.com/it/u=1970091545,917553451&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333",
      age: Math.floor(Math.random() * 10) + 1,
      gender: i % 2 === 0 ? 1 : 2,
      status: status,
      description:
        "这是一只非常可爱的" +
        (i % 2 === 0 ? "小猫" : "小狗") +
        "，它非常友好，适合家庭饲养。" +
        (status === "1"
          ? "它正在等待一个温暖的家。"
          : status === "2"
          ? "它已有人预定领养，等待确认中。"
          : "它已经找到幸福的家了！"),
    });
  }
  petList.value = mockData;
  total.value = mockData.length * 3; // 模拟总数
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  // 使用递归函数在分类树中查找指定ID的分类
  function findCategory(categories, id) {
    for (const category of categories) {
      if (category.categoryId == id) {
        return category;
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children, id);
        if (found) return found;
      }
    }
    return null;
  }

  const category = findCategory(categoryOptions.value, categoryId);
  return category ? category.categoryName : categoryId;
};

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.status = route.query.status || "";
  queryParams.categoryId = route.query.categoryId || "";
  queryParams.keyword = "";
  queryParams.pageNum = 1;
  getList();
};

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page;
  getList();
};

// 跳转到宠物详情
const goToDetail = (id) => {
  router.push(`/pet/detail/${id}`);
};

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.status !== undefined) {
      queryParams.status = newQuery.status;
    }
    if (newQuery.categoryId !== undefined) {
      queryParams.categoryId = newQuery.categoryId;
    }
    handleQuery();
  },
  { immediate: false, deep: true }
);

// 初始化
onMounted(async () => {
  await getCategoryData();
  await getList();
});
</script>

<style scoped>
.pet-list-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
}

.list-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-title {
  font-size: 20px;
  margin: 0;
  display: flex;
  align-items: center;
}

.list-title .el-tag {
  margin-left: 10px;
}

.list-info {
  color: #606266;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.pet-list {
  min-height: 300px;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
  font-size: 16px;
}

.pet-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  cursor: pointer;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.pet-image {
  position: relative;
  height: 180px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.pet-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.pet-info {
  padding: 15px 0;
}

.pet-name {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.pet-category {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.pet-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.pet-description {
  margin: 0;
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
  }

  .filter-form .el-form-item {
    margin-right: 0;
  }
}
</style>
